package com.edu.bhu.admin.controller.admin;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import com.edu.bhu.admin.controller.common.CommonController;
import com.edu.bhu.admin.domain.HouHouse;
import com.edu.bhu.admin.domain.HouImages;
import com.edu.bhu.admin.service.IHouHouseService;
import com.edu.bhu.common.config.OverallConfig;
import com.edu.bhu.common.config.ServerConfig;
import com.edu.bhu.common.utils.DateUtils;
import com.edu.bhu.common.utils.ShiroUtils;
import com.edu.bhu.common.utils.StringUtils;
import com.edu.bhu.common.utils.file.FileUploadUtils;
import com.edu.bhu.common.utils.file.FileUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.edu.bhu.common.annotation.Log;
import com.edu.bhu.common.enums.BusinessType;
import com.edu.bhu.admin.domain.HouRecord;
import com.edu.bhu.admin.service.IHouRecordService;
import com.edu.bhu.common.core.controller.BaseController;
import com.edu.bhu.common.core.domain.AjaxResult;
import com.edu.bhu.common.utils.poi.ExcelUtil;
import com.edu.bhu.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 租房记录Controller
 * 
 * @author zhangkeyi
 * @date 2022-02-22
 */
@Controller
@RequestMapping("/admin/record")
public class HouRecordController extends BaseController
{
    private static final Logger log = LoggerFactory.getLogger(HouRecordController.class);

    private String prefix = "admin/record";

    @Autowired
    private IHouRecordService houRecordService;

    @Autowired
    private IHouHouseService houHouseService;

    @Autowired
    private ServerConfig serverConfig;

    /**
     * 查询我的租房记录列表
     */
    @RequiresPermissions("admin:myrecord:view")
    @GetMapping("/myRecord")
    public String myRecord()
    {
        return prefix + "/myRecord";
    }

    /**
     * 查询我的出租记录列表
     */
    @RequiresPermissions("admin:rentrecord:view")
    @GetMapping("/rentRecord")
    public String rentRecord()
    {
        return prefix + "/rentRecord";
    }

    /**
     * 查询租房记录列表
     */
    @RequiresPermissions("admin:record:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(HouRecord houRecord)
    {
        startPage();
        List<HouRecord> list = houRecordService.selectHouRecordList(houRecord);
        return getDataTable(list);
    }

    /**
     * 查询租房记录列表（关联明细）
     */
    @RequiresPermissions("admin:record:list")
    @PostMapping("/listWithDetail/{type}")
    @ResponseBody
    public TableDataInfo listWithDetail(@PathVariable("type")Long type, HouRecord houRecord)
    {
        Long userId = ShiroUtils.getSysUser().getUserId();
        if(userId != 1)//todo 管理员可以看见所有的列表 测试完再改过来
        if(type == 1){
            //查看我的租房记录列表
            houRecord.setUserId(userId);
        }else if(type == 2){
            //查看我的出租记录列表
            HouHouse houHouse = new HouHouse();
            houHouse.setUserId(userId);
            houRecord.setHouHouse(houHouse);
        }
        startPage();
        List<HouRecord> list = houRecordService.selectHouRecordListWithDetail(houRecord);
        //筛选对应状态的条目
        if (houRecord.getRentStatus() != null)
        {
            list = list.stream().filter(item ->
                    item.getRentStatus() == houRecord.getRentStatus()
            ).collect(Collectors.toList());
        }
        return getDataTable(list);
    }

    /**
     * 导出租房记录列表
     */
    @RequiresPermissions("admin:record:export")
    @Log(title = "租房记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(HouRecord houRecord)
    {
        List<HouRecord> list = houRecordService.selectHouRecordList(houRecord);
        ExcelUtil<HouRecord> util = new ExcelUtil<HouRecord>(HouRecord.class);
        return util.exportExcel(list, "租房记录数据");
    }

    /**
     * 新增租房记录
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存租房记录
     */
    @RequiresPermissions("admin:record:add")
    @Log(title = "租房记录", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(HouRecord houRecord)
    {
        return toAjax(houRecordService.insertHouRecord(houRecord));
    }

    /**
     * 修改租房记录
     */
    @RequiresPermissions("admin:record:edit")
    @GetMapping("/edit/{recordId}")
    public String edit(@PathVariable("recordId") Long recordId, ModelMap mmap)
    {
        HouRecord houRecord = houRecordService.selectHouRecordByRecordId(recordId);
        mmap.put("houRecord", houRecord);
        return prefix + "/edit";
    }

    /**
     * 修改保存租房记录
     */
    @RequiresPermissions("admin:record:edit")
    @Log(title = "租房记录", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(HouRecord houRecord)
    {
        if(houRecord.getStatus() == 2){
            HouRecord entity = houRecordService.selectHouRecordByRecordId(houRecord.getRecordId());
            //退房请求，把房屋状态置为未出租
            HouHouse houHouse = new HouHouse();
            houHouse.setHouseId(entity.getHouseId());
            houHouse.setRentStatus(1L);
            houHouseService.updateHouHouse(houHouse);
        }
        return toAjax(houRecordService.updateHouRecord(houRecord));
    }

    /**
     * 删除租房记录
     */
    @RequiresPermissions("admin:record:remove")
    @Log(title = "租房记录", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(houRecordService.deleteHouRecordByRecordIds(ids));
    }

    /**
     * 选择延期时间
     */
    @RequiresPermissions("admin:rentrecord:view")
    @GetMapping("/goCheckout/{id}")
    public String goAddLoan(@PathVariable("id") String id, ModelMap mmap)
    {
        mmap.put("recordId",id);
        return prefix + "/checkout";
    }

    /**
     * 新增延期时间（月）
     */
    @RequiresPermissions("admin:record:edit")
    @Log(title = "租房记录", businessType = BusinessType.UPDATE)
    @PostMapping( "/checkoutAdd")
    @ResponseBody
    public AjaxResult checkoutAdd(Long id, Long extendTime)
    {
        HouRecord entity = houRecordService.selectHouRecordByRecordId(id);//拿到当前记录
        HouRecord houRecord = new HouRecord();//用来做更新的对象
        houRecord.setRecordId(id);//要更新记录的id

        Date endTime = DateUtils.getDatePlusDays(entity.getEndTime(),extendTime * 30);//计算结束日期
        houRecord.setEndTime(endTime);//将新的时间存入

        HouHouse house = houHouseService.selectHouHouseByHouseId(entity.getHouseId());//拿到房屋信息
        BigDecimal price = house.getPrice().multiply(BigDecimal.valueOf(extendTime));//计算新增月数要付的钱
        BigDecimal totalPrice = price.add(entity.getPrice());//计算总价
        houRecord.setPrice(totalPrice);//将总价存入

        return toAjax(houRecordService.updateHouRecord(houRecord));
    }

    /**
     * 选择文件页面
     */
    @RequiresPermissions("admin:rentrecord:view")
    @GetMapping("/goUpload/{id}")
    public String goUpload(@PathVariable("id") String id, ModelMap mmap)
    {
        mmap.put("recordId",id);
        return prefix + "/uploadFile";
    }

    /**
     * 上传附件
     */
    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult uploadFile(MultipartFile file, Long id) throws Exception
    {
        try
        {
            // 上传文件路径
            String filePath = OverallConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();

            //路径存入数据库
            HouRecord houRecord = new HouRecord();
            houRecord.setContract(fileName);
            houRecord.setRecordId(id);
            houRecordService.updateHouRecord(houRecord);

            ajax.put("fileName", fileName);
            ajax.put("url", url);
            return ajax;
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

}
